import { FetchAPI, PageParams, Pager, UserPermission, UserPermissionService } from '../../interface'
import * as fs from 'node:fs';
import * as utils from 'node:util';

const writeFilePromise = utils.promisify(fs.writeFile);

export class UserPermissionServiceImpl implements UserPermissionService {
    private db_path: string;
    private items: UserPermission[];
    private saveFile: () => Promise<void> = async () => {
        await writeFilePromise(this.db_path, JSON.stringify(this.items, null, 2));
    }
    constructor (db_path: string) {
        if (!fs.existsSync(db_path)) {
            fs.writeFileSync(db_path, '[]');
        }
        this.db_path = db_path;
        this.items = JSON.parse(fs.readFileSync(db_path, 'utf-8'));
    }
    permissionCreate: FetchAPI<UserPermission[]> = async (items) => {
        if (items.length === 0) return { success: false, msg: '请至少添加一个权限' };
        const uniq = new Set(items.map(t => t.key).concat(this.items.map(t => t.key))).size === items.length + this.items.length;
        if (!uniq) {
            return { success: false, msg: '权限重复' };
        }
        for(let item of items) {
            this.items.push(item);
        }
        await this.saveFile();
        return { success: true, }
    };
    permissionDelete: FetchAPI<UserPermission['key'][]> = async (keys) => {
        this.items = this.items.filter(p => keys.indexOf(p.key) === -1);
        await this.saveFile();
        return { success: true, }
    };
    permissionUpdate: FetchAPI<Partial<UserPermission>> = async (item) => {
        this.items = this.items.map(p => {
            if (p.key === item.key) {
                return { ...p, ...item };
            } else {
                return p;
            }
        });
        await this.saveFile();
        return { success: true, }
    };
    permissionList: FetchAPI<PageParams<Partial<UserPermission>>, Pager<UserPermission>> = async (body) => {
        const { page = 1, pageSize = 10, params } = body;
        let list = this.items;
        if (params) {
            const { key, name, desc, readonly } = params;
            list = this.items.filter(p => {
                if (key && p.key !== key) return false;
                if (name && !p.name.includes(name)) return false;
                if (desc && !p.desc?.includes(desc)) return false;
                if (readonly !== undefined && p.readonly !== readonly) return false;
                return true;
            });
        }
        return {
            success: true,
            data: {
                total: list.length,
                list: list.slice((page - 1) * pageSize, page * pageSize),
                page,
                pageSize,
            },
        }
    };
}
